package com.vvv.designpattern.synchronizedpattern;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author vvv
 * @date 2023-10-17 10 38
 * discription
 */
public class AlternatingReentrantLock {
    public static void main(String[] args) {
        MyReentrantLock myReentrantLock = new MyReentrantLock(5);
        Condition condition1 = myReentrantLock.newCondition();
        Condition condition2 = myReentrantLock.newCondition();
        Condition condition3 = myReentrantLock.newCondition();
        new Thread(() -> {
            myReentrantLock.print("a", condition1, condition2);
        }).start();
        new Thread(() -> {
            myReentrantLock.print("b", condition2, condition3);
        }).start();
        new Thread(() -> {
            myReentrantLock.print("c", condition3, condition1);
        }).start();
        myReentrantLock.lock();
        try {
            System.out.println("main start");
            condition1.signal();
        } finally {
            myReentrantLock.unlock();
        }
    }
}
/**
 *输出    自己的标记   下一次标记
 * a        1       2
 * b        2       3
 * c        3       1
 */
class MyReentrantLock extends ReentrantLock {
    // 循环次数
    private Integer loopNumber;

    public void print(String output, Condition current, Condition next) {
        for (int i = 0; i < loopNumber; i++) {
            lock();
            try {
                current.await();
                System.out.print(output);
                next.signal();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                unlock();
            }
        }
    }

    public MyReentrantLock(Integer loopNumber) {
        this.loopNumber = loopNumber;
    }
}
